import { setState } from './index'
import {
  apiGetWechatInfo,
  apiSaveWecahrtUserInfo,
  apiGetUserInfo,
  apiCheckInfo,
  apiImproveInfo,
  apiGetTravelers,
  apiAddTraveler,
  apiUpdateTraveler,
  apiDeleteTraveler
} from '@/api/user'

const state = {
  isLogin: false,
  userInfo: {},
  travelers: [],
  // 根据用户信息完成情况,判断是否可下单
  canOrder: false
}

const mutations = { setState }

const actions = {
  async signIn({ rootState, commit, dispatch }, infoFromFront) {
    const token = rootState.Client.token
    try {
      const info = infoFromFront || (await apiGetWechatInfo())
      await apiSaveWecahrtUserInfo(token, info)
      const userInfo = await apiGetUserInfo(token)
      const canOrder = await apiCheckInfo(token)
      commit('setState', { isLogin: true, userInfo, canOrder })
      dispatch('getTravelers')
      dispatch('MyTravel/getTravels', null, { root: true })
      console.log('用户授权成功')
      return Promise.resolve()
    } catch (err) {
      console.error('用户授权失败', err)
      return Promise.reject(err)
    }
  },

  async updateInfo({ rootState, commit }, info) {
    const token = rootState.Client.token
    try {
      await apiImproveInfo(token, info)
      const userInfo = await apiGetUserInfo(token)
      const canOrder = await apiCheckInfo(token)
      commit('setState', { userInfo, canOrder })
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  // 出行人管理
  async getTravelers({ rootState, commit }) {
    const token = rootState.Client.token
    try {
      const travelers = await apiGetTravelers(token)
      commit('setState', { travelers })
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  async addTraveler({ rootState, dispatch }, data) {
    const token = rootState.Client.token
    try {
      await apiAddTraveler(token, data)
      dispatch('getTravelers')
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  async updateTraveler({ rootState, dispatch }, data) {
    const token = rootState.Client.token
    try {
      await apiUpdateTraveler(token, data)
      dispatch('getTravelers')
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  async deleteTraveler({ rootState, dispatch }, id) {
    const token = rootState.Client.token
    try {
      await apiDeleteTraveler(token, id)
      dispatch('getTravelers')
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
